using Game.Networking.Server;
using SMGCore;
using System.Collections.Generic;
using UnityEngine;
using Voxels;

namespace Game {
	public sealed class AsteroidGenerator : ManualSingleton<AsteroidGenerator> {
		public Gradient ColorVariation;

		public static List<BlockType> AsteroidBlockSpawnTable = new List<BlockType>() { BlockType.Stone, BlockType.Stone, BlockType.Stone, BlockType.RedBlock, BlockType.Clay, BlockType.IronOre, BlockType.Sand, BlockType.CoalOre, BlockType.Cobblestone, BlockType.Cobblestone,
			BlockType.Stone,BlockType.Stone,BlockType.Stone, BlockType.Air, BlockType.GoldBlock, BlockType.IronBlock, BlockType.Stone,BlockType.Stone, BlockType.Sand, BlockType.Cobblestone, BlockType.CoalOre, BlockType.IronBlock};

		public SingleChunkProcessor GenerateNewAsteroid(Vector3 position, float radius) {
			var data = GenerateSpheroid(0, radius, position);
			var asteroid = ServerEntityController.Instance.CreateNewEntity(EntityType.BlockGrid, position, Vector3.zero, e => {
				var cast = (SingleChunkProcessor)e;
				cast.Setup(data);
			});
			return (SingleChunkProcessor)asteroid;
		}


		Chunk GenerateSpheroid(int index, float radius, Vector3 pos) {
			var data = new ChunkData();
			data.Index = index;
			data.Origin = pos;
			data.Blocks = new BlockDataHolder(Chunk.CHUNK_SIZE_X, Chunk.CHUNK_SIZE_Y, Chunk.CHUNK_SIZE_Z);

			var center = new Vector3(Chunk.CHUNK_SIZE_X, Chunk.CHUNK_SIZE_Y, Chunk.CHUNK_SIZE_Z) * 0.5f;
			for ( int i = 0; i < data.Blocks.Data.Length; i++ ) {
				var y = i / (Chunk.CHUNK_SIZE_X * Chunk.CHUNK_SIZE_Z);
				var xz = i % (Chunk.CHUNK_SIZE_X * Chunk.CHUNK_SIZE_Z);
				var z = xz / (Chunk.CHUNK_SIZE_X);
				var x = xz % (Chunk.CHUNK_SIZE_Z);
				var dist = Vector3.Distance(center, new Vector3(x, y, z));
				if ( dist < radius ) {
					var rawCol = ColorVariation.Evaluate(Random.Range(0, 1f));
					var blockType = AsteroidBlockSpawnTable[Random.Range(0, AsteroidBlockSpawnTable.Count)];
					data.Blocks.Data[i] = new BlockData(blockType, 0, 255, 0, ColorUtils.ConvertTo565(rawCol), 0);
				} else {
					data.Blocks.Data[i] = new BlockData(BlockType.Air, 0, 255, 0, 65535, 0);
				}

			}
			return new Chunk(data);
		}
	}
}

